<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <div class="flex gap-10px flex-wrap p-2">
      <div
        v-for="(item, index) in options"
        :key="index"
        class="w-65px h-65px hover:border hover:border-solid hover:border-gray-500 cursor-pointer rounded-md flex items-center justify-center"
        :class="{
          'border-solid': currentRecord.value == item.value,
          'border-gray-500': currentRecord.value == item.value,
          border: currentRecord.value == item.value,
        }"
        @click="handleClick(item)"
      >
        <img class="w-50px h-50px" :src="item.url" />
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { isEmpty } from '/@/utils/is';
  export default defineComponent({
    name: 'SelectIconModal',
    components: { BasicModal },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const { createMessage } = useMessage();
      const userStore = useUserStore();
      const serverInfo = userStore.getServerInfo;

      let options = ref<Recordable[]>([]);
      const currentRecord = ref<Recordable>({});

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '982px' });
        isUpdate.value = !!data?.isUpdate;
        options.value = data.options;
        if (options.value && options.value.length) {
          options.value.forEach((item) => {
            item.url = item.value
              ? serverInfo.rootPath +
                '/static' +
                (item.value && item.value.startsWith('/') ? item.value : `/${item.value}`)
              : '';
          });
        }
      });

      const getTitle = '选择图标';

      const handleClick = (record) => {
        currentRecord.value = record;
      };

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          if (isEmpty(currentRecord.value)) {
            createMessage.warning('选择数据不能为空');
            return;
          }
          closeModal();
          emit('success', currentRecord.value);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerModal,
        getTitle,
        handleSubmit,
        options,
        handleClick,
        currentRecord,
      };
    },
  });
</script>
